import QtQuick 2.12
import QtQuick.Controls 2.12
import QtLocation 5.12
import QtPositioning 5.12

Rectangle {
    id: tiledMapViewer
    color: "#f0f0f0"
    
    // ==================== 属性定义 ====================
    
    // 地图中心坐标
    property double centerLon: 109.240150
    property double centerLat: 23.724696
    property int zoomLevel: 16
    
    // 状态属性
    property bool isMapReady: false  // 改名避免与信号冲突
    property bool mapLoading: true
    
    // 路径规划属性
    property bool pathEditMode: false
    property bool showRobotPosition: true
    property real pathLineWidth: 3.0
    property color pathLineColor: "#e74c3c"
    property color pathPointColor: "#3498db"
    property color robotPositionColor: "#27ae60"
    
    // 路径点模型
    property alias pathPointsModel: pathPointsModel
    property alias robotPositionsModel: robotPositionsModel
    // 在属性定义区域添加以下别名
    property alias fieldPointsModel: fieldPointsModel
    property alias pathPointsModel: pathPointsModel
    property alias robotPositionsModel: robotPositionsModel

    // ==================== 信号定义 ====================
    
    signal mapReady()  // 地图准备完成信号
    signal locationChanged(real lon, real lat)
    signal mapClicked(real lon, real lat)
    signal pathPointAdded(real lon, real lat, int index)
    signal pathPointRemoved(int index)
    signal pathChanged()
    // 注意：zoomLevel属性会自动生成zoomLevelChanged()信号，无需手动声明
    
    // ==================== 数据模型 ====================
    
    ListModel {
        id: pathPointsModel
    }
    
    ListModel {
        id: robotPositionsModel
    }
    
    ListModel {
        id: routePathModel
    }
    
    // ==================== 地图插件配置 ====================
    
    Plugin {
        id: mapPlugin
        name: "osm"  // OpenStreetMap插件
        
        // 注意：osm插件不支持custom.host参数（Qt 5.12限制）
        // 要使用高德地图，需要将QtLocationPlugin编译为Qt Location插件
        // 参考：MAP_FIX_SOLUTION.md 方案3
        
        PluginParameter {
            name: "osm.mapping.cache.directory"
            value: "MapCache"
        }
        
        PluginParameter {
            name: "osm.mapping.cache.disk.size"
            value: "104857600"  // 100MB缓存
        }
        
        PluginParameter {
            name: "osm.useragent"
            value: "甘蔗农机智能管控平台/1.0"
        }
    }
    
    // ==================== 地图组件 ====================
    
    Map {
        id: map
        anchors.fill: parent
        plugin: mapPlugin
        center: QtPositioning.coordinate(centerLat, centerLon)
        zoomLevel: tiledMapViewer.zoomLevel
        
        // 地图手势
        gesture.enabled: true
        gesture.acceptedGestures: MapGestureArea.PinchGesture | MapGestureArea.PanGesture | MapGestureArea.FlickGesture
        
        // 复制方式
        copyrightsVisible: false
        
        Component.onCompleted: {
            console.log("地图组件初始化完成")
            console.log("地图插件:", plugin.name)
            console.log("地图中心:", center.latitude, center.longitude)
            console.log("缩放级别:", zoomLevel)
            
            mapLoading = false
            isMapReady = true
            tiledMapViewer.mapReady()  // 发送信号
        }
        
        onCenterChanged: {
            centerLon = center.longitude
            centerLat = center.latitude
            locationChanged(centerLon, centerLat)
        }
        
        onZoomLevelChanged: {
            tiledMapViewer.zoomLevel = Math.round(zoomLevel)
            // Qt会自动触发zoomLevelChanged信号，无需手动调用
        }
        
        // ==================== 地图点击事件 ====================
        
        MouseArea {
            id: mapMouseArea
            anchors.fill: parent
            acceptedButtons: Qt.LeftButton | Qt.RightButton
            
            onClicked: {
                var coordinate = map.toCoordinate(Qt.point(mouse.x, mouse.y))
                var lon = coordinate.longitude
                var lat = coordinate.latitude
                
                console.log("地图点击:", lon.toFixed(8), lat.toFixed(8))
                
                // 路径编辑模式
                if (pathEditMode && mouse.button === Qt.LeftButton) {
                    addPathPoint(lon, lat)
                } else if (pathEditMode && mouse.button === Qt.RightButton) {
                    removeNearestPathPoint(lon, lat)
                } else {
                    mapClicked(lon, lat)
                }
            }
        }
        
        // ==================== 路径点标记 ====================
        
        MapItemView {
            model: pathPointsModel
            delegate: MapQuickItem {
                coordinate: QtPositioning.coordinate(model.lat, model.lon)
                anchorPoint.x: pathMarker.width / 2
                anchorPoint.y: pathMarker.height / 2
                
                sourceItem: Rectangle {
                    id: pathMarker
                    width: 24
                    height: 24
                    radius: 12
                    color: pathPointColor
                    border.color: "white"
                    border.width: 2
                    
                    Text {
                        anchors.centerIn: parent
                        text: (index + 1).toString()
                        color: "white"
                        font.pixelSize: 10
                        font.bold: true
                    }
                    
                    // 点击删除
                    MouseArea {
                        anchors.fill: parent
                        enabled: pathEditMode
                        onClicked: {
                            removePathPoint(index)
                        }
                    }
                }
            }
        }
        
        // ==================== 机器人位置标记 ====================
        
        MapItemView {
            model: robotPositionsModel
            visible: showRobotPosition
            delegate: MapQuickItem {
                coordinate: QtPositioning.coordinate(model.lat, model.lon)
                anchorPoint.x: robotMarker.width / 2
                anchorPoint.y: robotMarker.height / 2
                
                sourceItem: Column {
                    id: robotMarker
                    spacing: 4
                    
                    // 机器人标签
                    Rectangle {
                        width: snText.width + 12
                        height: 20
                        color: robotPositionColor
                        radius: 4
                        border.color: "white"
                        border.width: 1
                        
                        Text {
                            id: snText
                            anchors.centerIn: parent
                            text: model.sn
                            color: "white"
                            font.pixelSize: 10
                            font.bold: true
                        }
                    }
                    
                    // 机器人圆点
                    Rectangle {
                        width: 16
                        height: 16
                        radius: 8
                        color: robotPositionColor
                        border.color: "white"
                        border.width: 2
                        anchors.horizontalCenter: parent.horizontalCenter
                    }
                }
            }
        }
        
        // ==================== 路径线绘制 ====================
        
        MapPolyline {
            id: pathLine
            line.width: pathLineWidth
            line.color: pathLineColor
            path: {
                var pathCoords = []
                for (var i = 0; i < pathPointsModel.count; i++) {
                    var point = pathPointsModel.get(i)
                    pathCoords.push(QtPositioning.coordinate(point.lat, point.lon))
                }
                return pathCoords
            }
        }
        
        // ==================== 规划路线绘制 ====================
        
        MapPolyline {
            id: routeLine
            line.width: 4
            line.color: "#2196f3"
            path: {
                var routeCoords = []
                for (var i = 0; i < routePathModel.count; i++) {
                    var point = routePathModel.get(i)
                    routeCoords.push(QtPositioning.coordinate(point.lat, point.lon))
                }
                return routeCoords
            }
        }
    }
    
    // ==================== 地图控制按钮 ====================
    
    Column {
        anchors.right: parent.right
        anchors.top: parent.top
        anchors.margins: 16
        spacing: 8
        z: 100
        
        // 放大按钮
        Button {
            width: 40
            height: 40
            text: "+"
            font.pixelSize: 20
            font.bold: true
            
            background: Rectangle {
                color: parent.pressed ? "#e0e0e0" : "white"
                radius: 4
                border.color: "#ccc"
                border.width: 1
            }
            
            onClicked: {
                zoomIn()
            }
        }
        
        // 缩小按钮
        Button {
            width: 40
            height: 40
            text: "−"
            font.pixelSize: 20
            font.bold: true
            
            background: Rectangle {
                color: parent.pressed ? "#e0e0e0" : "white"
                radius: 4
                border.color: "#ccc"
                border.width: 1
            }
            
            onClicked: {
                zoomOut()
            }
        }
        
        // 定位按钮
        Button {
            width: 40
            height: 40
            text: "⌖"
            font.pixelSize: 20
            
            background: Rectangle {
                color: parent.pressed ? "#e0e0e0" : "white"
                radius: 4
                border.color: "#ccc"
                border.width: 1
            }
            
            onClicked: {
                resetCenter()
            }
        }
    }
    
    // ==================== 缩放级别显示 ====================
    
    Rectangle {
        anchors.bottom: parent.bottom
        anchors.left: parent.left
        anchors.margins: 16
        width: zoomText.width + 16
        height: 30
        color: "white"
        radius: 4
        border.color: "#ccc"
        border.width: 1
        z: 100
        
        Text {
            id: zoomText
            anchors.centerIn: parent
            text: "缩放: " + tiledMapViewer.zoomLevel
            font.pixelSize: 12
        }
    }
    
    // ==================== 加载提示 ====================
    
    Rectangle {
        anchors.fill: parent
        color: "#cc000000"
        visible: mapLoading
        z: 200
        
        Column {
            anchors.centerIn: parent
            spacing: 20
            
            BusyIndicator {
                running: mapLoading
                width: 80
                height: 80
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            Label {
                text: "正在加载地图瓦片..."
                font.pixelSize: 18
                font.bold: true
                color: "white"
                anchors.horizontalCenter: parent.horizontalCenter
            }
        }
    }
    
    // ==================== JavaScript函数 ====================
    
    // 地图操作函数
    function zoomIn() {
        if (tiledMapViewer.zoomLevel < map.maximumZoomLevel) {
            tiledMapViewer.zoomLevel++
            map.zoomLevel = tiledMapViewer.zoomLevel
        }
    }
    
    function zoomOut() {
        if (tiledMapViewer.zoomLevel > map.minimumZoomLevel) {
            tiledMapViewer.zoomLevel--
            map.zoomLevel = tiledMapViewer.zoomLevel
        }
    }
    
    function resetCenter() {
        map.center = QtPositioning.coordinate(23.724696, 109.240150)
        tiledMapViewer.zoomLevel = 16
        map.zoomLevel = 16
    }
    
    function setMapCenter(lon, lat, zoom) {
        map.center = QtPositioning.coordinate(lat, lon)
        if (zoom !== undefined) {
            tiledMapViewer.zoomLevel = zoom
            map.zoomLevel = zoom
        }
    }
    
    function setZoomLevel(level) {
        tiledMapViewer.zoomLevel = Math.max(map.minimumZoomLevel, Math.min(map.maximumZoomLevel, level))
        map.zoomLevel = tiledMapViewer.zoomLevel
    }
    
    // 路径点操作函数
    function addPathPoint(lon, lat) {
        pathPointsModel.append({
            lon: lon,
            lat: lat,
            timestamp: new Date().toISOString()
        })
        
        console.log("添加路径点:", lon, lat, "总数:", pathPointsModel.count)
        pathPointAdded(lon, lat, pathPointsModel.count - 1)
        pathChanged()
        
        return true
    }
    
    function removePathPoint(index) {
        if (index >= 0 && index < pathPointsModel.count) {
            pathPointsModel.remove(index)
            console.log("删除路径点，索引:", index)
            pathPointRemoved(index)
            pathChanged()
            return true
        }
        return false
    }
    
    function removeNearestPathPoint(lon, lat) {
        if (pathPointsModel.count === 0) return false
        
        var minDistance = Number.MAX_VALUE
        var nearestIndex = -1
        
        for (var i = 0; i < pathPointsModel.count; i++) {
            var point = pathPointsModel.get(i)
            var distance = Math.sqrt(
                Math.pow(point.lon - lon, 2) + Math.pow(point.lat - lat, 2)
            )
            
            if (distance < minDistance) {
                minDistance = distance
                nearestIndex = i
            }
        }
        
        // 如果距离小于0.001度（约100米），则删除
        if (minDistance < 0.001) {
            return removePathPoint(nearestIndex)
        }
        
        return false
    }
    
    function clearPath() {
        if (pathPointsModel.count === 0) {
            return false
        }
        
        pathPointsModel.clear()
        pathEditMode = false
        
        console.log("已清除所有路径点")
        pathChanged()
        
        return true
    }
    
    function getPathPoints() {
        var points = []
        for (var i = 0; i < pathPointsModel.count; i++) {
            var point = pathPointsModel.get(i)
            points.push({
                lon: point.lon,
                lat: point.lat,
                timestamp: point.timestamp
            })
        }
        return points
    }
    
    function setPathPoints(points) {
        clearPath()
        for (var i = 0; i < points.length; i++) {
            var point = points[i]
            addPathPoint(point.lon, point.lat)
        }
    }
    
    function calculatePathLength() {
        if (pathPointsModel.count < 2) return 0
        
        var totalLength = 0
        for (var i = 0; i < pathPointsModel.count - 1; i++) {
            var point1 = pathPointsModel.get(i)
            var point2 = pathPointsModel.get(i + 1)
            
            // Haversine公式计算距离
            var R = 6371000 // 地球半径（米）
            var dLat = (point2.lat - point1.lat) * Math.PI / 180
            var dLon = (point2.lon - point1.lon) * Math.PI / 180
            var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                    Math.cos(point1.lat * Math.PI / 180) * Math.cos(point2.lat * Math.PI / 180) *
                    Math.sin(dLon/2) * Math.sin(dLon/2)
            var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
            totalLength += R * c
        }
        
        return totalLength
    }
    
    // 路径编辑模式控制
    function enablePathEditMode() {
        pathEditMode = true
        console.log("启用路径编辑模式")
    }
    
    function disablePathEditMode() {
        pathEditMode = false
        console.log("禁用路径编辑模式")
    }
    
    function togglePathEditMode() {
        pathEditMode = !pathEditMode
        console.log("路径编辑模式:", pathEditMode ? "启用" : "禁用")
    }
    
    // 机器人位置更新
    function updateRobotPosition(sn, lon, lat, status) {
        // 查找现有机器人
        for (var i = 0; i < robotPositionsModel.count; i++) {
            var robot = robotPositionsModel.get(i)
            if (robot.sn === sn) {
                robotPositionsModel.set(i, {
                    sn: sn,
                    lon: lon,
                    lat: lat,
                    timestamp: new Date().toISOString(),
                    status: status || "在线"
                })
                console.log("更新机器人位置:", sn, lon, lat)
                return true
            }
        }
        
        // 添加新机器人
        robotPositionsModel.append({
            sn: sn,
            lon: lon,
            lat: lat,
            timestamp: new Date().toISOString(),
            status: status || "在线"
        })
        
        console.log("添加机器人位置:", sn, lon, lat)
        return true
    }
    
    // 设置规划路线
    function setRoutePath(path) {
        routePathModel.clear()
        
        for (var i = 0; i < path.length; i++) {
            var point = path[i]
            routePathModel.append({
                lon: point.lon,
                lat: point.lat
            })
        }
        
        console.log("设置规划路线，路径点数:", routePathModel.count)
    }
    
    function clearRoutePath() {
        routePathModel.clear()
        console.log("清除规划路线")
    }
    
    // 导出路径为KML
    function exportPathToKML() {
        if (pathPointsModel.count === 0) {
            console.warn("没有路径点可导出")
            return ""
        }
        
        var kmlContent = '<?xml version="1.0" encoding="UTF-8"?>\n'
        kmlContent += '<kml xmlns="http://www.opengis.net/kml/2.2">\n'
        kmlContent += '  <Document>\n'
        kmlContent += '    <name>作业路径</name>\n'
        kmlContent += '    <description>农机作业路径</description>\n'
        kmlContent += '    <Placemark>\n'
        kmlContent += '      <name>路径线</name>\n'
        kmlContent += '      <LineString>\n'
        kmlContent += '        <coordinates>\n'
        
        for (var i = 0; i < pathPointsModel.count; i++) {
            var point = pathPointsModel.get(i)
            kmlContent += '          ' + point.lon + ',' + point.lat + ',0\n'
        }
        
        kmlContent += '        </coordinates>\n'
        kmlContent += '      </LineString>\n'
        kmlContent += '    </Placemark>\n'
        kmlContent += '  </Document>\n'
        kmlContent += '</kml>\n'
        
        return kmlContent
    }
    
    Component.onCompleted: {
        console.log("TiledMapViewer初始化完成")
        console.log("地图中心:", centerLat, centerLon)
        console.log("缩放级别:", zoomLevel)
    }
}

